package framework.core
{
import flash.display.DisplayObject;
import flash.system.ApplicationDomain;
import flash.utils.Dictionary;

import mx.utils.UIDUtil;

public class UIWidget
{
	private static var domains:Dictionary = new Dictionary(true); /* ApplicationDomain */
	
	private static var classMap:Dictionary = new Dictionary(true); /* ClassItem */
	
	private static var libs:WidgetComponentLib;
	
	public static function initialize():void
	{
		libs = new WidgetComponentLib();
		libs.initialize();
		
		domains["current"] = ApplicationDomain.currentDomain;
	}
	
	public static function getApplicationDomains():Dictionary
	{
		return domains;
	}
	
	public static function createUI(classRef:String):DisplayObject
	{
		var classItem:ClassItem = classMap[classRef];
		if (!classItem)
		{
			classItem = new ClassItem();
			classItem.classRef = classRef;
			
			for (var domainID:String in domains)
			{
				var domain:ApplicationDomain = domains[domainID];
				if (domain.hasDefinition(classRef))
				{
					classItem.domainID = domainID;
					classMap[classRef] = classItem;
					break;
				}
			}
		}
		var instance:DisplayObject = newInstance(classItem.classRef, classItem.domainID) as DisplayObject;
		
		return instance;
	}
	
	public static function registerAppDomain(domain:ApplicationDomain):void
	{
		domains[UIDUtil.createUID()] = domain;
	}
	
	public static function getClassReference(refStr:String):Class
	{
		for (var domainID:String in domains)
		{
			var domain:ApplicationDomain = domains[domainID];
			if (domain.hasDefinition(refStr))
			{
				return domain.getDefinition(refStr) as Class;
			}
		}
		return null;
	}
	
	private static function newInstance(classRef:String, domainID:String):*
	{
		var ref:Class = ApplicationDomain(domains[domainID]).getDefinition(classRef) as Class;
		return new ref();
	}
}
}

class ClassItem
{
	public var classRef:String;
	
	public var domainID:String;
}